<?php
declare(strict_types=1);

namespace App\Service;

use App\Helper\Log;
use App\Helper\Util;
use Hyperf\DbConnection\Db;
use App\Helper\Calendar;
use App\Service\UserService;
use App\Service\WxTemplateMessageService;
use App\Service\StatisrecService;

/**
 * 科室服务
 */
class OfficeService 
{
    private $office_id = 0;
    /**
     * [__construct description] 构造函数
     */
    public function __construct()
    {
    }
    /**
     * 设置全局科室ID
     * [setUserId description]
     * @param [type] $office_id [description]
     */
    public function setOfficeId($office_id)
    {
        $this->office_id = $office_id;
    }
    /**
     * 创建科室
     * [createOffice description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function createOffice($params)
    {
        $hospital_name = Db::table('conf_hospital')
            ->where("id",$params['hospital_id'])
            ->value("name");
        $office_type_name = Db::table('conf_office')
            ->where("id",$params['office_type_id'])
            ->value("name");
        $insert_data = [
            'name'=>$params['name'],
            'hospital_id'=>$params['hospital_id'],
            'hospital_name'=>$hospital_name,
            'office_type'=>$params['office_type_id'],
            'office_type_name'=>$office_type_name,
            'created_at'=>time()
        ];
        $office_id = Db::table('office')->insertGetId($insert_data);
        $params['office_id'] = $office_id;
        $params['role'] = "cap";
        $this->addMember($params);
        //初始化班次
        $this->initTrad($params);
        //初始化科室设置
        $this->initOfficeSet($params);
        $return_data = [
            'office_id' => $office_id,
            'role' => "cap"
        ];
        return $return_data;
    }
    /**
     * 修改科室
     * [updateOffice description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function updateOffice($params)
    {
        if(!empty($params['office_id'])){
            $save_data = [
                'updated_at'=>time()
            ];
            if(!empty($params['name'])){
                $save_data['name'] = $params['name'];
            }
            if(!empty($params['hospital_id'])){
                $save_data['hospital_id'] = $params['hospital_id'];
                $save_data['hospital_name'] = Db::table('conf_hospital')
                    ->where("id",$params['hospital_id'])
                    ->value("name");
            }
            if(!empty($params['office_type_id'])){
                $save_data['office_type'] = $params['office_type_id'];
                $save_data['office_type_name'] = Db::table('conf_office')
                    ->where("id",$params['office_type_id'])
                    ->value("name");
            }
            if(!empty($params['user_name'])){
                $cap_id = Db::table('office_member')
                    ->where(['office_id'=>$params['office_id'],'status'=>1,'is_del'=>0,'role'=>'cap'])
                    ->value("user_id");
                Db::table('user')
                    ->where(['id'=>$cap_id])
                    ->update(['realname'=>$params['user_name']]);
            }
            $res = Db::table('office')
                ->where(['id'=>$params['office_id']])
                ->update($save_data);
        }
        return true;
    }
    /**
     * 创建或加入时校验是否已经存在科室
     * [checkExists description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function checkExists($user_id)
    {
        $data = Db::table('office_member')
            ->select(['office_id','role'])
            ->where(['is_del'=>0,'status'=>1,'user_id'=>$user_id])
            ->first();
        if(!empty($data)){
            return true;
        }
        return false;
    }
    /**
     * 添加成员
     * [addMember description]
     * @param [type] $params [description]
     */
    public function addMember($params)
    {
        if(empty($params['office_id']) || empty($params['user_id']) || empty($params['role'])){
            return false;
        }
        $insert_data = [
            'office_id'=>$params['office_id'],
            'user_id'=>$params['user_id'],
            'role'=>$params['role'],
            'created_at'=>time()
        ];
        Db::table('office_member')->insert($insert_data);
        $update_data = [
            'realname'=>$params['user_name']
        ];
        Db::table('user')->where('id', $params['user_id'])->update($update_data);
        return true;
    }
    /**
     * 获取科室基本信息
     * [baseInfo description]
     * @return [type] [description]
     */
    public function baseInfo()
    {
        $office_info = Db::table('office')
            ->select(['id','name','hospital_id','hospital_name','office_type','office_type_name'])
            ->where("id",$this->office_id)
            ->first();
        $cap_info = Db::table('office_member')
            ->select(['user_id'])
            ->where(['office_id'=>$this->office_id,'role'=>"cap",'is_del'=>0,'status'=>1])
            ->first();
        if(!empty($cap_info['user_id'])){
            $user_info = Db::table('user')
                ->select(['realname'])
                ->where("id",$cap_info['user_id'])
                ->first();
            $cap_info['cap_name'] = $user_info['realname']??"";
        }
        $return_data = [
            'office_info' => $office_info,
            'cap_info' => $cap_info
        ];
        return $return_data;
    }
    /**
     * 全部成员信息
     * [membersInfo description]
     * @return [type] [description]
     */
    public function membersInfo($user_id)
    {
        $office_info = Db::table('office')
            ->select(['id','name'])
            ->where("id",$this->office_id)
            ->first();
        $members_info = Db::table('office_member')
            ->select(['user_id','role','sort'])
            ->where(['office_id'=>$this->office_id,'is_del'=>0,'status'=>1])
            ->orderBy('sort', 'desc')
            ->get()
            ->toArray();
        if(!empty($members_info)){
            foreach ($members_info as &$member) {
                $user_info = Db::table('user')
                    ->select(['avatar','realname'])
                    ->where("id",$member['user_id'])
                    ->first();
                $member['realname'] = $user_info['realname']??"";
                $member['avatar'] = $user_info['avatar']??"";
                $sub_info = (new UserService($member['user_id']))->checkSubStatus();
                $member['is_subwx'] = $sub_info['spb'];
                if($member['user_id']==$user_id){
                    $member['is_myself'] = 1;
                }else{
                    $member['is_myself'] = 0;
                }
            }
        }
        $return_data = [
            'office_id'=>$office_info['id'],
            'office_name'=>$office_info['name'],
            'totle_member'=>count($members_info),
            'members'=>$members_info
        ];
        return $return_data;
    }
    /**
     * 成员详情
     * [membersDetail description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function memberDetail($user_id)
    {
        $member = Db::table('office_member')
            ->select(['user_id','role','sort'])
            ->where(['office_id'=>$this->office_id,'user_id'=>$user_id,'is_del'=>0,'status'=>1])
            ->first();
        if(!empty($member)){
            $user_info = Db::table('user')
                ->select(['avatar','realname','phone'])
                ->where("id",$member['user_id'])
                ->first();
            $member['realname'] = $user_info['realname']??"";
            $member['avatar'] = $user_info['avatar']??"";
            $member['phone'] = $user_info['phone']??"";

            $office_user_info = Db::table('office_member_info')
                ->select(['positional','level','education','ycapital','workno','workbed','remark'])
                ->where(['office_id'=>$this->office_id,'user_id'=>$user_id])
                ->first();
            $member['positional_id'] = $office_user_info['positional']??0;
            $member['positional'] = Db::table('conf_positional')
                ->where("id",$member['positional_id'])
                ->value("name");
            $member['level_id'] = $office_user_info['level']??0;
            $member['level'] = Db::table('conf_nurse_level')
                ->where("id",$member['level_id'])
                ->value("name");
            $member['education_id'] = $office_user_info['education']??0;
            $member['education'] = Db::table('conf_education')
                ->where("id",$member['education_id'])
                ->value("name");
            $member['ycapital'] = $office_user_info['ycapital']??"";
            $member['workno'] = $office_user_info['workno']??"";
            $member['workbed'] = $office_user_info['workbed']??"";
            $member['remark'] = $office_user_info['remark']??"";
        }
        return $member;
    }
    /**
     * 保存成员详情
     * [memberSave description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function memberSave($params)
    {
        if(!empty($params['member_id'])){
            $user_save_data = [
                'updated_at'=>time()
            ];
            if(!empty($params['avatar'])){
                $user_save_data['avatar'] = $params['avatar'];
            }
            if(!empty($params['realname'])){
                $user_save_data['realname'] = $params['realname'];
            }
            if(!empty($params['phone'])){
                $user_save_data['phone'] = $params['phone'];
            }
            Db::table('user')
                ->where(['id'=>$params['member_id']])
                ->update($user_save_data);

            $office_member_info_id = Db::table('office_member_info')
                ->where(['office_id'=>$this->office_id,'is_del'=>0,'status'=>1,"user_id"=>$params['member_id']])
                ->value("id");
            if(!empty($office_member_info_id)){
                $save_data = [
                    'updated_at'=>time()
                ];
                if(!empty($params['positional'])){
                    $save_data['positional'] = $params['positional'];
                }
                if(!empty($params['level'])){
                    $save_data['level'] = $params['level'];
                }
                if(!empty($params['education'])){
                    $save_data['education'] = $params['education'];
                }
                if(!empty($params['ycapital'])){
                    $save_data['ycapital'] = $params['ycapital'];
                }
                if(!empty($params['workno'])){
                    $save_data['workno'] = $params['workno'];
                }
                if(!empty($params['workbed'])){
                    $save_data['workbed'] = $params['workbed'];
                }
                if(!empty($params['remark'])){
                    $save_data['remark'] = $params['remark'];
                }
                Db::table('office_member_info')
                    ->where(['id'=>$office_member_info_id])
                    ->update($save_data);
            }else{
                $save_data = [
                    'office_id'=>$this->office_id,
                    'user_id'=>$params['member_id'],
                    'positional'=>$params['positional']??0,
                    'level'=>$params['level']??0,
                    'education'=>$params['education']??0,
                    'ycapital'=>$params['ycapital']??"",
                    'workno'=>$params['workno']??"",
                    'workbed'=>$params['workbed']??"",
                    'remark'=>$params['remark']??"",
                    'created_at'=>time()
                ];
                Db::table('office_member_info')
                    ->insert($save_data);
            }
        }
        return true;
    }
    /**
     * 检查是否是科室创建者
     * [checkIsCap description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function checkIsCap($user_id)
    {
        $member_info = Db::table('office_member')
            ->select(['role'])
            ->where(['office_id'=>$this->office_id,'user_id'=>$user_id,'is_del'=>0,'status'=>1])
            ->first();
        if(!empty($member_info['role']) && $member_info['role']=="cap"){
            return true;
        }
        return false;
    }
    /**
     * 检查是否是科室成员
     * [checkIsMember description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function checkIsMember($user_id)
    {
        $member_info = Db::table('office_member')
            ->select(['role'])
            ->where(['office_id'=>$this->office_id,'user_id'=>$user_id,'is_del'=>0,'status'=>1])
            ->first();
        if(!empty($member_info)){
            return true;
        }
        return false;
    }
    /**
     * 保存成员排序
     * [saveMemberSort description]
     * @param  [type] $member_id [description]
     * @param  [type] $sort      [description]
     * @return [type]            [description]
     */
    public function saveMemberSort($member_id,$sort)
    {
        $res = Db::table('office_member')
            ->where(['office_id'=>$this->office_id,'user_id'=>$member_id])
            ->update(['sort'=>$sort,'updated_at'=>time()]);
        if($res){
            return true;
        }
        return false;
    }
    /**
     * 检查科室是否存在
     * [checkExistsOffice description]
     * @return [type] [description]
     */
    public function checkExistsOffice()
    {
        $office = Db::table('office')
            ->select(['id'])
            ->where(['id'=>$this->office_id,'is_del'=>0,'status'=>1])
            ->first();
        if(!empty($office)){
            return true;
        }
        return false;
    }
    /**
     * 解散科室
     * [delOffice description]
     * @return [type] [description]
     */
    public function delOffice()
    {
        $ores = Db::table('office')
            ->where(['id'=>$this->office_id])
            ->update(['is_del'=>1,'updated_at'=>time()]);
        $omres = Db::table('office_member')
            ->where(['office_id'=>$this->office_id])
            ->update(['is_del'=>1,'updated_at'=>time()]);
        if($ores && $omres){
            return true;
        }
        return false;
    }
    /**
     * 退出科室
     * [quitOffice description]
     * @return [type] [description]
     */
    public function quitOffice($params)
    {
        return $this->delMember($params['user_id']);
    }
    /**
     * 删除成员
     * [delMember description]
     * @param  [type] $member_id [description]
     * @return [type]            [description]
     */
    public function delMember($member_id)
    {
        $res = Db::table('office_member')
            ->where(['office_id'=>$this->office_id,'user_id'=>$member_id])
            ->update(['is_del'=>1,'updated_at'=>time()]);
        if($res){
            return true;
        }
        return false;
    }
    /**
     * 保存排班信息-保存并发布
     * [saveCalendar description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function saveCalendar($params)
    {
        $data = json_decode($params['data'],true);
        if(empty($data)){
            return false;
        }
        $need_notice_user = [];
        foreach ($data as $user_info) {
            $user_id = $user_info['user_id']??0;
            $user_name = $user_info['user_name']??"";
            $cal_info = $user_info['list']??[];
            $need_notice_this_one = false;
            $need_notice_this_one_add = [];
            $need_notice_this_one_change = [];
            if(empty($user_id) || empty($cal_info)){
                continue;
            }
            foreach ($cal_info as $trad) {
                if(empty($trad['list'])){
                    $aimp_id = NULL;
                }else{
                    $aimp_id = array_column($trad['list'], "trad_id");
                }
                $aimp_id = array_column($trad['list'], "trad_id");
                if(!empty($aimp_id)){
                    $trad_ids = ",".implode(",", $aimp_id).",";
                }else{
                    $trad_ids = "";
                }
                $where = [
                    'office_id'=>$this->office_id,
                    'user_id'=>$user_id,
                    'wdate'=>$trad['wdate']
                ];
                $save_data = [
                    'trad_id'=>$trad_ids
                ];
                $iou = Db::table('office_calendar')
                    ->select(['id','trad_id'])
                    ->where($where)
                    ->first();
                if(empty($iou)){
                    $save_data['office_id'] = $this->office_id;
                    $save_data['user_id'] = $user_id;
                    $save_data['wdate'] = $trad['wdate'];
                    $save_data['created_at'] = time();
                    $res = Db::table('office_calendar')
                        ->insert($save_data);
                    $need_notice_this_one = true;
                    $need_notice_this_one_add[] = $trad['wdate'];
                }else{
                    $save_data['updated_at'] = time();
                    $res = Db::table('office_calendar')
                        ->where($where)
                        ->update($save_data);
                    if($iou['trad_id']!=$trad_ids){
                        $need_notice_this_one = true;
                        $need_notice_this_one_change[] = [
                            'wdate'=>$trad['wdate'],
                            'ori_trad'=>$iou['trad_id'],
                            'now_trad'=>$trad_ids
                        ];
                    }
                }
            }
            if($need_notice_this_one){
                $need_notice_user[$user_info['user_id']] = [
                    'add'=>$need_notice_this_one_add,
                    'change'=>$need_notice_this_one_change
                ];
            }
        }
        $this->noticeUserChange($need_notice_user);
        $this->saveCalendarTemp($params);
        return true;
    }
    /**
     * 保存排班信息-仅保存
     * [saveCalendarTemp description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function saveCalendarTemp($params)
    {
        $data = json_decode($params['data'],true);
        if(empty($data)){
            return false;
        }
        foreach ($data as $user_info) {
            $user_id = $user_info['user_id']??0;
            $user_name = $user_info['user_name']??"";
            $cal_info = $user_info['list']??[];
            if(empty($user_id) || empty($cal_info)){
                continue;
            }
            foreach ($cal_info as $trad) {
                if(empty($trad['list'])){
                    $aimp_id = NULL;
                }else{
                    $aimp_id = array_column($trad['list'], "trad_id");
                }
                if(!empty($aimp_id)){
                    $trad_ids = ",".implode(",", $aimp_id).",";
                }else{
                    $trad_ids = "";
                }
                $where = [
                    'office_id'=>$this->office_id,
                    'user_id'=>$user_id,
                    'wdate'=>$trad['wdate']
                ];
                $save_data = [
                    'trad_id'=>$trad_ids
                ];
                $iou = Db::table('office_calendar_temp')
                    ->select(['id','trad_id'])
                    ->where($where)
                    ->first();
                if(empty($iou)){
                    $save_data['office_id'] = $this->office_id;
                    $save_data['user_id'] = $user_id;
                    $save_data['wdate'] = $trad['wdate'];
                    $save_data['created_at'] = time();
                    $res = Db::table('office_calendar_temp')
                        ->insert($save_data);
                }else{
                    $save_data['updated_at'] = time();
                    $res = Db::table('office_calendar_temp')
                        ->where($where)
                        ->update($save_data);
                }
            }
        }
        return true;
    }
    /**
     * 通知用户变更
     * [noticeUserChange description]
     * @param  [type] $users [description]
     * @return [type]        [description]
     */
    public function noticeUserChange($users)
    {
        if(empty($users)){
            return false;
        }
        $office_name = Db::table('office')
            ->where('id', $this->office_id)
            ->value("name");
        $cap_id = Db::table('office_member')
            ->where(['office_id'=>$this->office_id,'status'=>1,'is_del'=>0,'role'=>'cap'])
            ->value("user_id");
        $cap_name = Db::table('user')
            ->where('id', $cap_id)
            ->value("realname");
        $wxtplServ = new WxTemplateMessageService();
        foreach ($users as $user_id => $data) {
            $user_info = Db::table('user')
                ->select(['wx_openid','unionid'])
                ->where('id', $user_id)
                ->first();
            if(empty($user_info['wx_openid'])){
                $user_openid = Db::table('wxship_act')
                    ->where('unionid', $user_info['unionid'])
                    ->value("openid");
            }else{
                $user_openid = $user_info['wx_openid'];
            }
            if(!empty($data['add'])){
                if(count($data['add'])>1){
                    $content = $data['add'][0]."~".$data['add'][count($data['add'])-1];
                }else{
                    $content = $data['add'][0];
                }
                $msg_data = [
                    'openid'=>$user_openid,
                    'cap'=>$cap_name,
                    'office'=>$office_name,
                    'content'=>$content
                ];
                $wxtplServ->noticeUserTradAdd($msg_data);

                //统计推送用户数据
                $staServ = new StatisrecService();
                $static_params = [
                    'device'=>"applet",
                    'tag'=>'notice_user',
                    'save_type'=>'normal'
                ];
                $staServ->doSave($static_params);
            }
            if(!empty($data['change'])){
                foreach ($data['change'] as $change_data) {
                    $ori_ids = array_filter(explode(",", $change_data['ori_trad']));
                    $ori_names = Db::table('office_trad')
                        ->whereIn('id', $ori_ids)
                        ->pluck("name")
                        ->toArray();
                    $ori_names = "原排班【".implode("、", $ori_names)."】";
                    $now_ids = array_filter(explode(",", $change_data['now_trad']));
                    $now_names = Db::table('office_trad')
                        ->whereIn('id', $now_ids)
                        ->pluck("name")
                        ->toArray();
                    $now_names = "现排班【".implode("、", $now_names)."】";

                    $msg_data = [
                        'openid'=>$user_openid,
                        'cap'=>$cap_name,
                        'office'=>$office_name,
                        'wdate'=>$change_data['wdate'],
                        'ori_text'=>$ori_names,
                        'now_text'=>$now_names,
                    ];
                    $wxtplServ->noticeUserTradChange($msg_data);
                }

                //统计推送用户数据
                $staServ = new StatisrecService();
                $static_params = [
                    'device'=>"applet",
                    'tag'=>'notice_user',
                    'save_type'=>'normal'
                ];
                $staServ->doSave($static_params);
            }
        }
        return true;
    }
    /**
     * 初始化默认班次
     * [initTrad description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function initTrad($params)
    {
        $default_data = Db::table('conf_trad')
            ->select(['type','name','color','work_time','work_hours','coe','sort'])
            ->where(['status'=>1,'is_del'=>0])
            ->get()
            ->toArray();
        foreach ($default_data as $key => &$value) {
            $value['office_id'] = $params['office_id'];
            $value['created_at'] = time();
        }
        Db::table('office_trad')
            ->insert($default_data);
        return true;
    }
    /**
     * 初始化科室设置
     * [initOfficeSet description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function initOfficeSet($params)
    {
        $default_data = [
            'office_id'=>$params['office_id'],
            'tmod'=>1,
            'tunit'=>1,
            'tbed'=>1,
            'work_cycle'=>40,
            'work_day'=>8,
            'created_at'=>time()
        ];
        Db::table('office_set')
            ->insert($default_data);
        return true;
    }
    /**
     * 获取科室班次
     * [getTrads description]
     * @return [type] [description]
     */
    public function getTrads()
    {
        $trad = Db::table('office_trad')
            ->select(['id','office_id','type','name','color','work_time','work_hours','coe'])
            ->where(['status'=>1,'is_del'=>0,'office_id'=>$this->office_id])
            ->orderBy('sort', 'desc')
            ->get()
            ->toArray();
        if(!empty($trad)){
            foreach ($trad as &$tv) {
                $tv['work_time'] = json_decode($tv['work_time'],true);
                $tv['color_code'] = Db::table('conf_color')
                    ->where(['id'=>$tv['color']])
                    ->value("color");
            }
        }
        return $trad;
    }
    /**
     * 获取科室班次-包含隐藏的
     * [getTradsAll description]
     * @return [type] [description]
     */
    public function getTradsAll()
    {
        $trad = Db::table('office_trad')
            ->select(['id','office_id','type','name','color','work_time','work_hours','coe'])
            ->where(['is_del'=>0,'office_id'=>$this->office_id])
            ->orderBy('sort', 'desc')
            ->get()
            ->toArray();
        if(!empty($trad)){
            foreach ($trad as &$tv) {
                $tv['work_time'] = json_decode($tv['work_time'],true);
                $tv['color_code'] = Db::table('conf_color')
                    ->where(['id'=>$tv['color']])
                    ->value("color");
            }
        }
        return $trad;
    }
    /**
     * 获取科室成员日历
     * [getCalendar description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getCalendar($params)
    {
        if(empty($params['office_id'])){
            return NULL;
        }
        if(empty($params['begin_date']) || empty($params['end_date'])){
            $cal = Calendar::getWeekJustBeginAndEnd();
            $params['begin_date'] = $cal['first_date'];
            $params['end_date'] = $cal['last_date'];
        }
        $userServ = new UserService();
        $return_data = [];
        $return_list = [];
        $members = Db::table('office_member')
            ->select(['user_id'])
            ->where(['office_id'=>$this->office_id,'is_del'=>0,'status'=>1])
            ->orderBy('sort', 'desc')
            ->get()
            ->toArray();
        foreach ($members as $member) {
            $user_info = Db::table('user')
                ->select(['realname'])
                ->where("id",$member['user_id'])
                ->first();
            $params['user_id'] = $member['user_id'];
            $cal_info = $userServ->getOnePersonCalWithoutTotal($params);
            $return_list[] = [
                'user_id'=>$member['user_id'],
                'user_name'=>$user_info['realname']??"",
                'list'=>$cal_info
            ];
        }
        $return_data = [
            'is_public' =>1,
            'list'=>$return_list
        ];
        return $return_data;
    }
    /**
     * 获取科室成员日历-临时表
     * [getCalendarTemp description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getCalendarTemp($params)
    {
        if(empty($params['office_id'])){
            return NULL;
        }
        if(empty($params['begin_date']) || empty($params['end_date'])){
            $cal = Calendar::getWeekJustBeginAndEnd();
            $params['begin_date'] = $cal['first_date'];
            $params['end_date'] = $cal['last_date'];
        }
        $userServ = new UserService();
        $return_data = [];
        $return_list = [];
        $is_public = $userServ->checkPersonCalIsPublic($params);
        $members = Db::table('office_member')
            ->select(['user_id'])
            ->where(['office_id'=>$this->office_id,'is_del'=>0,'status'=>1])
            ->orderBy('sort', 'desc')
            ->get()
            ->toArray();
        foreach ($members as $member) {
            $user_info = Db::table('user')
                ->select(['realname'])
                ->where("id",$member['user_id'])
                ->first();
            $params['user_id'] = $member['user_id'];
            if($is_public){
                $cal_info = $userServ->getOnePersonCalWithoutTotal($params);
            }else{
                $cal_info = $userServ->getOnePersonCalTempWithoutTotal($params);
            }
            $return_list[] = [
                'user_id'=>$member['user_id'],
                'user_name'=>$user_info['realname']??"",
                'list'=>$cal_info
            ];
        }
        $return_data = [
            'is_public' =>$is_public?1:0,
            'list'=>$return_list
        ];
        return $return_data;
    }
    /**
     * 获取排班设置
     * [getOfficeSet description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getOfficeSet($params)
    {
        if(empty($params['office_id'])){
            return NULL;
        }
        $sets = Db::table('office_set')
            ->select(['id','office_id','tmod','tunit','tbed','work_cycle','work_day'])
            ->where(['is_del'=>0,'status'=>1,'office_id'=>$params['office_id']])
            ->first();
        if(!empty($sets)){
            $sets['tmod_name'] = Db::table('conf_tmod')
                ->where(['id'=>$sets['tmod']])
                ->value("name");
            $sets['tunit_name'] = Db::table('conf_tunit')
                ->where(['id'=>$sets['tunit']])
                ->value("name");
            $sets['tbed_name'] = Db::table('conf_tbed')
                ->where(['id'=>$sets['tbed']])
                ->value("name");
        }
        return $sets;
    }
    /**
     * 保存排班设置
     * [setOfficeSet description]
     * @param [type] $params [description]
     */
    public function saveOfficeSet($params)
    {
        $save_data = [
            'updated_at'=>time()
        ];
        if(!empty($params['tmod'])){
            $save_data['tmod'] = $params['tmod'];
        }
        if(!empty($params['tunit'])){
            $save_data['tunit'] = $params['tunit'];
        }
        if(!empty($params['tbed'])){
            $save_data['tbed'] = $params['tbed'];
        }
        if(isset($params['work_cycle'])){
            $save_data['work_cycle'] = $params['work_cycle'];
        }
        if(isset($params['work_day'])){
            $save_data['work_day'] = $params['work_day'];
        }
        $res = Db::table('office_set')
            ->where(['office_id'=>$this->office_id])
            ->update($save_data);
        return $res;
    }
    /**
     * 获取班种信息
     * [getOfficeTrad description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getOfficeTradDetail($params)
    {
        if(empty($params['office_id'])){
            return NULL;
        }
        if(empty($params['trad_id'])){
            return NULL;
        }
        $trads = Db::table('office_trad')
            ->select(['id','office_id','type','name','color','work_time','work_hours','coe','sort','status'])
            ->where(['is_del'=>0,'id'=>$params['trad_id']])
            ->first();
        if(!empty($trads)){
            $trads['work_time'] = json_decode($trads['work_time'],true);
            $trads['color_code'] = Db::table('conf_color')
                ->where(['id'=>$trads['color']])
                ->value("color");
        }
        return $trads;
    }
    /**
     * 保存科室班次信息
     * [saveOfficeTrad description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function saveOfficeTrad($params)
    {
        if(!empty($params['id'])){
            $save_data = [
                'updated_at'=>time()
            ];
            if(!empty($params['type'])){
                $save_data['type'] = $params['type'];
            }
            if(!empty($params['name'])){
                $save_data['name'] = $params['name'];
            }
            if(!empty($params['color'])){
                $save_data['color'] = $params['color'];
            }
            if(isset($params['work_time'])){
                $save_data['work_time'] = $params['work_time'];
            }
            if(isset($params['work_hours'])){
                $save_data['work_hours'] = $params['work_hours'];
            }
            if(isset($params['coe'])){
                $save_data['coe'] = $params['coe'];
            }
            if(isset($params['sort'])){
                $save_data['sort'] = $params['sort'];
            }
            if(isset($params['status']) && $params['status']!=-1){
                $save_data['status'] = $params['status'];
            }
            $res = Db::table('office_trad')
                ->where(['id'=>$params['id']])
                ->update($save_data);
        }else{
            $save_data = [
                'office_id'=>$this->office_id,
                'type'=>$params['type']??"",
                'name'=>$params['name']??"",
                'color'=>$params['color']??0,
                'work_time'=>$params['work_time']??"",
                'work_hours'=>$params['work_hours']??0,
                'coe'=>$params['coe']??0,
                'sort'=>$params['sort']??0,
                'status'=>$params['status']??0,
                'created_at'=>time()
            ];
            $res = Db::table('office_trad')
                ->insert($save_data);
        }
        return $res;
    }
    /**
     * 删除班次
     * [delOfficeTrad description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function delOfficeTrad($params)
    {
        if(!empty($params['id'])){
            $save_data = [
                'is_del'=>1,
                'updated_at'=>time()
            ];
            $res = Db::table('office_trad')
                ->where(['id'=>$params['id']])
                ->update($save_data);
        }
        return $res;
    }
    /**
     * 获取排班备注
     * [getCalendarRemark description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getCalendarRemark($params)
    {
        if(empty($params['office_id'])){
            return NULL;
        }
        $content = Db::table('office_remark')
            ->where(['is_del'=>0,'status'=>1,'office_id'=>$params['office_id'],'begin_date'=>$params['begin_date'],'end_date'=>$params['end_date']])
            ->value("content");
        return $content;
    }
    /**
     * 保存排班备注
     * [saveCalendarRemark description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function saveCalendarRemark($params)
    {
        if(empty($params['office_id'])){
            return NULL;
        }
        if(empty($params['begin_date'])){
            return NULL;
        }
        if(empty($params['end_date'])){
            return NULL;
        }
        if(empty($params['content'])){
            return NULL;
        }
        $data_id = Db::table('office_remark')
            ->where(['is_del'=>0,'status'=>1,'office_id'=>$params['office_id'],'begin_date'=>$params['begin_date'],'end_date'=>$params['end_date']])
            ->value("id");
        if(!empty($data_id)){
            $save_data = [
                'content'=>$params['content'],
                'updated_at'=>time()
            ];
            $res = Db::table('office_remark')
                ->where(['id'=>$data_id])
                ->update($save_data);
        }else{
            $save_data = [
                'office_id'=>$this->office_id,
                'begin_date'=>$params['begin_date'],
                'end_date'=>$params['end_date'],
                'content'=>$params['content']??"",
                'created_at'=>time()
            ];
            $res = Db::table('office_remark')
                ->insert($save_data);
        }
        return $res;
    }
    /**
     * 获取排班备注-导excel专用
     * [tradRemark description]
     * @return [type] [description]
     */
    public function tradRemark($begin_date,$end_date)
    {
        $where = [
            ['office_id', '=', $this->office_id],
            ['is_del', '=', 0],
            ['status', '=', 1],
            ['begin_date', '>=', $begin_date],
            ['end_date', '<=', $end_date],
        ];
        $remarks = Db::table('office_remark')
            ->select(['begin_date','end_date','content'])
            ->where($where)
            ->get()
            ->toArray();
        $return_data = "";
        if(!empty($remarks)){
            foreach ($remarks as $remark) {
                $cup = $remark['begin_date']."至".$remark['end_date']."排班备注说明：\n";
                $cup .= $remark['content']."\n\n";
                $return_data .= $cup;
            }
        }
        return $return_data;
    }
    /**
     * 成员批量排序
     * [memberBatchSort description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function memberBatchSort($data)
    {
        $data = json_decode($data, true);
        foreach ($data as $key => $value) {
            Db::table('office_member')
                ->where(['office_id'=>$this->office_id,'user_id'=>$value['id']])
                ->update(['sort'=>$value['sort']]);
        }
        return true;
    }
    /**
     * 班次批量排序
     * [tradBatchSort description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function tradBatchSort($data)
    {
        $data = json_decode($data, true);
        foreach ($data as $key => $value) {
            Db::table('office_trad')
                ->where(['id'=>$value['id']])
                ->update(['sort'=>$value['sort']]);
        }
        return true;
    }
    /**
     * 获取下一次应该排班的时间
     * [getNextTrad description]
     * @return [type] [description]
     */
    public function getNextTrad()
    {
        $last_one = Db::table('office_calendar')
            ->select(['wdate'])
            ->where(['office_id'=>$this->office_id,'is_del'=>0,'status'=>1])
            ->orderBy("wdate","desc")
            ->first();
        if(empty($last_one)){
            $res = Calendar::getWeekJustBeginAndEnd();
            $begin_date = $res['first_date'];
            $end_date = $res['last_date'];
        }else{
            //拼接后一周
            $last_day_in_week = date('w', strtotime($last_one['wdate']));
            if($last_day_in_week==0){
                $nt_idx = 1;
            }else{
                $nt_idx = 8-$last_day_in_week;
            }
            $next_week_first_day = date('Y-m-d', strtotime($last_one['wdate']." +".$nt_idx." day"));
            $res = Calendar::getWeekJustBeginAndEnd($next_week_first_day);
            $begin_date = $res['first_date'];
            $end_date = $res['last_date'];
        }
        $return_data = [
            'begin_date' => $begin_date,
            'end_date' => $end_date
        ];
        return $return_data;
    }
    /**
     * 排班校验
     * [checkEmpty description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function checkEmpty($params)
    {
        $data = $params['data']['list'];
        if(empty($data)){
            return false;
        }
        $trad = Db::table('office_trad')
            ->select(['id','name'])
            ->where(['is_del'=>0,'office_id'=>$this->office_id])
            ->orderBy('sort', 'desc')
            ->get()
            ->toArray();
        if(empty($trad)){
            return false;
        }
        $date_array = [];
        foreach ($data[0]['list'] as $datev) {
            $date_array[$datev['wdate']] = [
                'wdate' => $datev['wdate'],
                'number' => 0
            ];
        }
        $trad_array = [];
        foreach ($trad as $tv) {
            $trad_array[$tv['id']] = [
                'trad_id'=>$tv['id'],
                'trad_name'=>$tv['name'],
                'total_number'=>0,
                'list'=>$date_array
            ];
        }
        foreach ($data as $dv) {
            foreach ($dv['list'] as $dlv) {
                if(!empty($dlv['list'])){
                    foreach ($dlv['list'] as $dllv) {
                        $dllv['user_id'] = $dv['user_id'];
                        $trad_array[$dllv['trad_id']]['list'][$dlv['wdate']]['number'] += 1;
                        $trad_array[$dllv['trad_id']]['total_number'] += 1;
                    }
                }
            }
        }
        foreach ($trad_array as $key => &$value) {
            $value['list'] = array_values($value['list']);
        }
        $trad_array = array_values($trad_array);
        return $trad_array;
    }
}
